"""
FileName：cart_page.py
Description：
Author：gaojiahui
Time：2025/8/29 18:38
Website：https://gitee.com/gao-jiahui
"""
from selenium.webdriver.common.by import By

from pages.base_page import BasePage


class CartPage(BasePage):
    """购物车页面"""
    # 元素定位
    CART_ITEMS = (By.CSS_SELECTOR, "div.shop-goods-item-wrap.el-row")
    ITEM_NAME = (By.CSS_SELECTOR, "a.sku-name")
    ITEM_PRICE = (By.CSS_SELECTOR, "div.sku-total div.price-text")
    ITEM_QUANTITY = (By.CSS_SELECTOR, "input[type='number']")
    SUBTOTAL = (By.CSS_SELECTOR, "b.price div.price-text")
    CHECKOUT_BUTTON = (By.CSS_SELECTOR, "a.check-btn")
    EMPTY_CART_MESSAGE = (By.CSS_SELECTOR, "div.empty-cart")
    SELECT_ALL_CHECKBOX = (By.CSS_SELECTOR, "a.check.check-all")
    CLEAR_CART_BUTTON = (By.LINK_TEXT, "清空购物车")

    def get_cart_items_count(self):
        """获取购物车商品数量"""
        return len(self.find_elements(self.CART_ITEMS))

    def get_item_names(self):
        """获取购物车商品名称"""
        item_names = []
        for item in self.find_elements(self.ITEM_NAME):
            item_names.append(item.text)
        return item_names

    def get_item_prices(self):
        """获取购物车商品价格"""
        item_prices = []
        for item in self.find_elements(self.ITEM_PRICE):
            item_prices.append(float(item.text.replace("¥", "")))
        return item_prices

    def get_item_quantities(self):
        """获取购物车商品数量"""
        item_quantities = []
        for item in self.find_elements(self.ITEM_QUANTITY):
            item_quantities.append(int(item.get_attribute("title")))
        return item_quantities

    def get_subtotal(self):
        """获取购物车商品总价"""
        return float(self.get_text(self.SUBTOTAL).replace("¥", ""))

    def proceed_to_checkout(self):
        """继续结账"""
        self.click(self.CHECKOUT_BUTTON)
        # 点击继续结账按钮后会跳转结账页面
        from pages.checkout_page import CheckoutPage
        return CheckoutPage(self.driver)

    def select_all_items(self):
        """全选购物车商品"""
        # 首先判断购物车是否全选
        if not self.is_element_selected(self.SELECT_ALL_CHECKBOX):
            self.click(self.SELECT_ALL_CHECKBOX)
        else:
            print("购物车已全选")

    def clear_cart(self):
        """清空购物车"""
        self.click(self.CLEAR_CART_BUTTON)

    def is_empty(self):
        """判断购物车是否为空"""
        return self.is_element_present(self.EMPTY_CART_MESSAGE)
